package cn.xluobo.business.wechat.miniapp.base.controller;

import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.xluobo.business.sys.admin.repo.model.SysUser;
import cn.xluobo.business.sys.admin.service.ISysUserTenantService;
import cn.xluobo.business.sys.staff.service.ISysStaffService;
import cn.xluobo.business.wechat.miniapp.base.domain.req.ReqBindUser;
import cn.xluobo.business.wechat.miniapp.base.domain.req.ReqSyncUserInfo;
import cn.xluobo.business.wechat.miniapp.base.service.WechatMiniBaseService;
import cn.xluobo.business.wechat.user.service.IWechatUserInfoService;
import cn.xluobo.config.login.LoginTypeEnum;
import cn.xluobo.config.login.LoginUser;
import cn.xluobo.config.tenant.TenantContextHolder;
import cn.xluobo.core.api.APIResponse;
import cn.xluobo.core.api.ApiResEnums;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * @author ：KingLong
 * @date ：Created in 2020/10/15 09:40
 */
@RestController
@RequestMapping("/api/wechat/miniapp/{appId}/base")
public class WechatMiniBaseController {

    @Autowired
    private WechatMiniBaseService wechatMiniAppService;
    @Autowired
    private IWechatUserInfoService wechatUserInfoService;
    @Autowired
    private ISysStaffService staffService;
    @Autowired
    private ISysUserTenantService userTenantService;

    /**
     * 根据code登录
     * @param appId
     * @param code
     * @param password
     * @return
     */
    @PostMapping("/login/{code}")
    public APIResponse login(@PathVariable String appId, @PathVariable String code, String password) {
        if(StringUtils.isAnyEmpty(appId,code, password)) {
            return APIResponse.toExceptionResponse("appId or code or password is  null");
        }
        WxMaJscode2SessionResult wxMaJscode2Session = wechatMiniAppService.getWxMaJscode2Session(appId, code);
        if(null == wxMaJscode2Session) {
            return APIResponse.toExceptionResponse(ApiResEnums.PARAM_FAIL);
        }

        SysUser sysUser = wechatUserInfoService.getSysUser(appId, wxMaJscode2Session.getOpenid());
        if(null == sysUser) {
            return APIResponse.toExceptionResponse(ApiResEnums.MINI_APP_UN_BIND_USER);
        }

        Map accessTokenByMiniAppCode = wechatMiniAppService.getAccessTokenByMiniAppOpenid(appId, wxMaJscode2Session.getOpenid(), "");
        String error = MapUtils.getString(accessTokenByMiniAppCode, "error");
        if (error != null) {
            String errorDescription = MapUtils.getString(accessTokenByMiniAppCode, "error_description");
            return APIResponse.toExceptionResponse(errorDescription);
        }
        String refreshToken = MapUtils.getString(accessTokenByMiniAppCode, "refresh_token");
        String accessToken = MapUtils.getString(accessTokenByMiniAppCode, "access_token");

        LoginUser loginUser = wechatMiniAppService.getLoginUserByAccessToken(accessToken);
        loginUser.setLoginType(LoginTypeEnum.WECHAT_MINI_APP.getLoginType());
        loginUser.setExtendOjb(wxMaJscode2Session);

        try {
            String tenantId = userTenantService.selectUserDefaultTenant(loginUser.getUserId());
            TenantContextHolder.setTenant(tenantId);

            Long staffId = staffService.getStaffIdByUserId(loginUser.getUserId());
            loginUser.setStaffId(staffId);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            TenantContextHolder.remove();
        }

        wechatMiniAppService.putOnlineUser(loginUser, accessToken, refreshToken);
        return APIResponse.toAPIResponse(accessToken);
    }

    /**
     * 绑定账号
     * @return
     */
    @PostMapping("/bind")
    public APIResponse bind(@RequestBody ReqBindUser reqBindUser) {
        return wechatMiniAppService.bindUser(reqBindUser);
    }

    /**
     * 同步微信用户信息
     * @return
     */
    @PostMapping("/syncWechatUserInfo")
    public APIResponse syncWechatUserInfo(@RequestBody ReqSyncUserInfo syncUserInfo) {
        return wechatMiniAppService.syncWechatUserInfo(syncUserInfo);
    }

    /**
     * 取消绑定当前账号
     * @return
     */
    @PostMapping("/unBind")
    public APIResponse unBind() {
        return wechatMiniAppService.unBindUser();
    }

}
